package com.kaifa.org.tp04.example02.dao.impl;

import com.kaifa.org.tp04.example02.bean.User;
import com.kaifa.org.tp04.example02.dao.UserDao;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.util.List;

/**
 * 实现用户信息的增删改查
 * 增：insert into语句，调用jdbcTemplate的update()方法，实现的是方法的重载
 * 删：delete from语句，调用jdbcTemplate的update()方法，实现的是方法的重载
 * 改：update set语句，调用jdbcTemplate的update()方法，实现的是方法的重载
 */

public class UserDaoImpl implements UserDao {
//    定义jdbcTemplate属性，并设置set方法
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public int addUser(User us) {
        String sql="insert into t_user(user_name,user_pwd) value(?,?)";
        Object[] args = new Object[]{us.getUserName(),us.getUserPwd()};
//        执行添加操作，返回sql语句影响的记录条数
        int i = jdbcTemplate.update(sql,args);
        return i;
    }

    public int updateUser(User us) {
        String sql="update t_user set user_name=?,user_pwd=? where id=?";
        Object[] args = new Object[]{us.getUserName(),us.getUserPwd(),us.getId()};
        int i = jdbcTemplate.update(sql,args);
        return i;
    }

    public int deleteUser(int id) {
        String sql="delete from t_user where id=?";
        int i = jdbcTemplate.update(sql,id);
        return i;
    }

    public User selectUserById(int id) {
        String sql = "select * from t_user where id=?";
//        创建对象
        RowMapper<User> rowMapper =new BeanPropertyRowMapper<User>(User.class);
        User us = jdbcTemplate.queryForObject(sql,rowMapper,id);
        return us;
    }

    public List<User> selectAllUser() {
        String sql = "select * from t_user";
//        创建对象
        RowMapper<User> rowMapper =new BeanPropertyRowMapper<User>(User.class);
        List<User> userList=jdbcTemplate.query(sql,rowMapper);
        return userList;
    }
}
